package com.shiguiwu.springboot3.aspect;

import com.shiguiwu.springboot3.dto.AuthUser;
import com.shiguiwu.springboot3.dto.request.LoginRequest;
import com.shiguiwu.springboot3.service.MemberLoginLogService;
import com.shiguiwu.springboot3.util.IpUtils;
import com.shiguiwu.springboot3.util.MemberContextUtils;
import com.shiguiwu.springboot3.util.ServletUtil;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * 会员登录日志
 *
 * @author stone
 */
@Slf4j
@Aspect
@Component
public class LoginLogAspect {

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private MemberLoginLogService memberLoginLogService;

    @Pointcut("@annotation(com.shiguiwu.springboot3.annotation.LoginAnnotation)"
            + "|| @within(com.shiguiwu.springboot3.annotation.LoginAnnotation)")
    public void loginPointCut() {

    }

    @Around("loginPointCut()")
    public Object around(ProceedingJoinPoint pj) throws Throwable {

        long start = System.currentTimeMillis();
        Object proceed = null;
        Object[] args = pj.getArgs();
        try {
            //如果需要重新设置参数，则调用proceed的有参方法，否则直接调用无参方法即可
            proceed = pj.proceed(args);

            handleLoginLog(false,"登录成功",new LoginRequest());
        } catch (Throwable throwable) {
            //handleLog(pj, throwable, null, start);
            LoginRequest request = (LoginRequest) args[0];
            handleLoginLog(true, throwable.getMessage(),request);
            throw throwable;
        }

        return proceed;
    }


    public void handleLoginLog(boolean isError, String msg, LoginRequest request) {
        try {
            String ip = IpUtils.getIpAddr();
            final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtil.getRequest().getHeader("User-Agent"));
            AuthUser err = new AuthUser();
            AuthUser currentMember = isError ? err : MemberContextUtils.getCurrentMember();
            err.setUsername(request.getUsername());
            taskExecutor.execute(() -> memberLoginLogService.saveLog(isError, msg, ip, userAgent, currentMember));
        } catch (Exception e) {
            log.info("登录日志记录报错{}",e.getMessage());
        }
    }
}

